package com.many.backs.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.many.backs.service.sys.SysUserService;
import com.many.common.exception.ErrorCodes;
import com.many.data.entity.SysUser;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2022-06-30
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/all")
    @Cacheable(value = "user_all",key = "#user")           //#user表示读取形参里名称为user的值，value表示缓存空间(自定义名称)
    public R page(Page page,SysUser user){
        LambdaQueryWrapper<SysUser>wrapper=new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(user.getUserName())){
            wrapper.like(SysUser::getUserName,user.getUserName());
        }
        wrapper.orderByDesc(SysUser::getCreateTime);
        return R.ok(sysUserService.page(page,wrapper));
    }

    @GetMapping("/all/{id}")
    @Cacheable(value = "user_id",key = "#id" ,condition = "#id==6")
    public R page(Page page,@PathVariable Integer id){
        return R.ok(sysUserService.getById(id));
    }


     @PostMapping("/update")
    public R<Boolean> R (SysUser user) {
      return R.ok(sysUserService.updates(user));
    }

    @PostMapping("/add")
    @CacheEvict(value = "user_all", allEntries = true)
    public R String (SysUser user){
        List<SysUser> list = sysUserService.list(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, user.getUserName()).eq(SysUser::getDeleteFlag, 0));
        if (!ObjectUtils.isEmpty(list)){
            return R.failed(ErrorCodes.USER_NAME_EXISTS);
        }
        return R.ok(sysUserService.save(user));
    }

    @DeleteMapping("/delete/{userId}")
    public R delete(@PathVariable Integer userId){
        return R.ok(sysUserService.removeById(userId));
    }

    @PostMapping("/logins")
    public R login(@RequestBody SysUser user){
        return R.ok(sysUserService.login(user));
    }

    @GetMapping("/sum")
    public R redis(){
        return R.ok(sysUserService.redis());
    }

    @GetMapping("/list")
    public R redisList(){
        return R.ok(sysUserService.redisList());
    }





}

